import {
  registApi,
  loginApi,
  loadApi
} from '../../api/customerApi.js'

import router from '../../router/index.js'

import {
  getToken,
  setToken
} from '../../utils/token.js'

export default {
  namespaced: true,
  state: {
    user_phone: '',
    user_password: '',
    confirm_password: '',
    user_name: '',
    user_info: null
  },
  getters: {},
  mutations: {
    set_user_info(state, val) {
      state.user_info = val
    }
  },
  actions: {
    //注册
    customer_regist(context) {
      //http://localhost:8001/api/regist
      registApi({
          'user_phone': context.state.user_phone,
          'user_password': context.state.user_password,
          'user_name': context.state.user_name
        }).then(function(response) {
          if (response.data.httpcode == 200) {
            //自动登录
            context.dispatch('customer_login')
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //登录
    customer_login(context) {
      loginApi({
        'username': context.state.user_phone,
        'password': context.state.user_password
      }).then(function(response) {
        if (response.data.httpcode == 200) {
          //保存令牌（token）
          setToken(response.data.data);
          //获取用户信息
          context.dispatch('customer_load');
          //跳转主页
          router.push({
            path: '/'
          })
        }
      })
    },
    //获取用户信息
    customer_load(context) {
      loadApi().then(function(response) {
        if (response.data.httpcode == 200) {
          console.log(response.data.data);
          context.commit('set_user_info', response.data.data);
        }
      })
    }
  }
}
